package com.alibaba.boot.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class NettyServer {

    public static void main(String[] args) throws Exception {


        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("heart beat thread start");

                while (true) {
                    while (NettyServerHandler.clientChannel != null) {
                        System.out.println("client active send beat begin");
                        NettyServerHandler.clientChannel.writeAndFlush(Unpooled.copiedBuffer("hello this is server beat".getBytes(StandardCharsets.UTF_8)));

                        try {
                            Thread.sleep(1000);
                        } catch (Exception e) {

                        }
                    }
                }

            }
        });

        //创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        //创建服务器端启动对象，配置参数
        ServerBootstrap bootstrap;
        try {
             bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128) //设置线程队列等待连接个数
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        //给 pipline设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new IdleStateHandler(3,7,10, TimeUnit.SECONDS));

                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("....server is  ready");
            //监听一个端口
            ChannelFuture channelFuture = bootstrap.bind(6668).sync();
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();


        }catch (Exception e){
            workerGroup.shutdownGracefully();
        }




    }
}
